﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Lead2012.Models;
using Lead2012.ViewModels;
using Lead2012.Helpers;
using Lead2012.Business;
using Lead2012.Utility;

namespace Lead2012.Repository
{
    public class DashboardManagementRepository : BaseManagementRepository
    {
        // Create an instance of entities framework
        Lead2012Entities entities = new Lead2012Entities();

        public void GetModel(ref DashboardViewModel model)
        {
            List<ItemFilter> listUserMetrics = new List<ItemFilter>();
            List<LeadSourceItem> listLeadSource = new List<LeadSourceItem>();

            DateTime startDate = LeadTools.StartOfDay(DateTime.Now);
            DateTime endDate = DateTime.Now;
            
            if (model.IsAdmin)
            {
                listUserMetrics = GetAllUsers();

                // Copy user list to display in Calendar Pannel
                List<ItemFilter> listUser = new List<ItemFilter>();
                if (listUserMetrics != null && listUserMetrics.Count > 0)
                    listUser.AddRange(listUserMetrics);

                ItemFilter user = new ItemFilter();
                user.ID = "0";
                user.ItemName = "Tất cả người dùng";
                listUserMetrics.Insert(0, user);

                //model.ListAgentForCalendar = listAgent;
                model.UserList = listUser;
                model.MetricUserList = listUserMetrics;
                model.MilestoneModel = GetMilestoneReport(0, 0, startDate, endDate);
            }
            else
            {
                ItemFilter user = new ItemFilter();
                user.ID = model.UserId.ToString();
                user.ItemName = model.Email;
                listUserMetrics.Add(user);
                model.UserList = listUserMetrics;
                model.MetricUserList = listUserMetrics;
                model.MilestoneModel = GetMilestoneReport(0, model.Header.UserId, startDate, endDate);
            }

            model.LeadSourceList = GetLeadSource();
            model.LeadFlowModel = GetLeadFlowStatistic(model.IsAdmin, model.Header.UserId);
            model.RangeReportList = GetRangeList();
            model.RangeList = GetRangeList();
            model.CalendarList = GetListCalendarEvent(int.Parse(model.UserId), DateTime.Now.ToString("dd/MM/yyyy"));
            model.TimeSelected = string.Format("{0}", LeadTools.GetTodayText());
        }

        #region #Common
        public MilestoneMetricsInfo GetMilestoneReport(int sourceId, int userId, DateTime startDate, DateTime endDate)
        {
            // Get all milestone info here
            // Params
            SqlParameter paramSource = new SqlParameter("@SourceId", DbType.Int32);
            paramSource.Value = sourceId;

            SqlParameter paramUser = new SqlParameter("@UserId", DbType.Int32);
            paramUser.Value = userId;

            SqlParameter paramStart = new SqlParameter("@StartDate", DbType.DateTime);
            paramStart.Value = startDate;

            SqlParameter paramEnd = new SqlParameter("@EndDate", DbType.DateTime);
            paramEnd.Value = endDate;

            // Execute a query
            List<StatisticFilter> list = new List<StatisticFilter>();
            using (SqlDataReader item = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.StoredProcedure, "GetMilestoneMetric", paramSource, paramUser, paramStart, paramEnd))
            {
                while (item.Read())
                {
                    StatisticFilter stat = new StatisticFilter();
                    stat.ItemName = item.GetString(1);
                    stat.ItemCount = item.GetInt32(2);
                    list.Add(stat);
                }
            }

            // Calculate with milestone options
            string None = string.Empty, Contacted = string.Empty, Rate = string.Empty;
            int totalLeads = list.Sum(c => c.ItemCount);
            if (totalLeads > 0)
            {
                // None
                if (list[0].ItemCount > 0)
                {
                    None = string.Format(@"{0} %", (((float)list[0].ItemCount / (float)totalLeads) * 100).ToString().Split('.')[0]);
                }
                else
                {
                    None = "N/A";
                }
                // Contacted
                if (list[1].ItemCount > 0)
                {
                    Contacted = string.Format("{0} %", (((float)list[1].ItemCount / (float)totalLeads) * 100).ToString().Split('.')[0]);
                }
                else
                {
                    Contacted = "N/A";
                }
                // Rate
                if (list[2].ItemCount > 0)
                {
                    Rate = string.Format("{0} %", (((float)list[2].ItemCount / (float)totalLeads) * 100).ToString().Split('.')[0]);
                }
                else
                {
                    Rate = "N/A";
                }
            }
            else
            {
                None = "N/A";
                Contacted = "N/A";
                Rate = "N/A";
            }


            // Display a summary info to admin/user
            MilestoneMetricsInfo model = new MilestoneMetricsInfo
            {
                None = None,
                Contacted = Contacted,
                Rate = Rate
            };
            return model;
        }

        public LeadFlowModel GetLeadFlowStatistic(bool isAdmin, int userId)
        {
            LeadFlowModel model = new LeadFlowModel();

            if (isAdmin)
                userId = 0;
            
            // Transform data
            // Get lead status here
            SqlParameter paramUser = new SqlParameter("@UserId", DbType.Int32);
            paramUser.Value = userId;

            // Execute a query
            List<SummaryInfo> listStatuses = new List<SummaryInfo>();
            using (SqlDataReader item = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.StoredProcedure, "GetStatisticByLeadStatus", paramUser))
            {
                while (item.Read())
                {
                    SummaryInfo modelStatus = new SummaryInfo();
                    modelStatus.Name = item.GetString(1);
                    modelStatus.Today = item.GetInt32(2);
                    modelStatus.Yesterday = item.GetInt32(3);
                    modelStatus.SevenDays = item.GetInt32(4);
                    modelStatus.Month = item.GetInt32(5);
                    modelStatus.TwoMonth = item.GetInt32(6);
                    modelStatus.ActiveTotal = item.GetInt32(7);
                    listStatuses.Add(modelStatus);
                }
            }

            listStatuses.Add(new SummaryInfo()
            {
                Name = "Tổng",
                Today = listStatuses.Sum(c => c.Today),
                Yesterday = listStatuses.Sum(c => c.Yesterday),
                SevenDays = listStatuses.Sum(c => c.SevenDays),
                Month = listStatuses.Sum(c => c.Month),
                TwoMonth = listStatuses.Sum(c => c.TwoMonth),
                ActiveTotal = listStatuses.Sum(c => c.ActiveTotal)
            });
            model.StatusSummaryInfo = listStatuses;

            // get lead source here
            if (isAdmin)
            {
                // Execute a query
                List<SummaryInfo> listSources = new List<SummaryInfo>();                
                using (SqlDataReader item = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.StoredProcedure, "GetStatisticByLeadSource"))
                {
                    while (item.Read())
                    {
                        SummaryInfo modelSource = new SummaryInfo();
                        modelSource.Name = item.GetString(1);
                        modelSource.Today = item.GetInt32(2);
                        modelSource.Yesterday = item.GetInt32(3);
                        modelSource.SevenDays = item.GetInt32(4);
                        modelSource.Month = item.GetInt32(5);
                        modelSource.TwoMonth = item.GetInt32(6);
                        modelSource.ActiveTotal = item.GetInt32(7);
                        listSources.Add(modelSource);
                    }
                }
                listSources.Add(new SummaryInfo()
                {
                    Name = "Tổng",
                    Today = listSources.Sum(c => c.Today),
                    Yesterday = listSources.Sum(c => c.Yesterday),
                    SevenDays = listSources.Sum(c => c.SevenDays),
                    Month = listSources.Sum(c => c.Month),
                    TwoMonth = listSources.Sum(c => c.TwoMonth),
                    ActiveTotal = listSources.Sum(c => c.ActiveTotal)
                });
                model.CampaignSummaryInfo = listSources;
            }

            model.TimeUpdate = "Cập nhật cuối " + System.DateTime.Now.ToString("t");

            return model;
        }

        public List<CalendarInfoItem> GetListCalendarEvent(int userId, string dateSelected)
        {
            string[] arr = dateSelected.Split('/');
            string currentDate = string.Format("{0}-{1}-{2}", arr[2], arr[1], arr[0]);
            List<CalendarInfoItem> calendarList = new List<CalendarInfoItem>();
            List<CalendarInfoEx> events = new LeadCalendarItemRepository().GetAllCalendarBy(userId, DateTime.Parse(currentDate));

            // Code get all calendar events here
            // First: Get all calendar events by lead id
            // Second: Filter all events by start/end time
            for (int i = 0; i < 11; i++)
            {
                CalendarInfoItem model = new CalendarInfoItem();

                TimeSpan span  = new TimeSpan(8 + i, 0, 0);
                string date = string.Format("{0} {1}:00:00", currentDate, (8 + i));
                string start = string.Format("{0} {1}:30:00", currentDate, (7 + i));
                string end = string.Format("{0} {1}:30:00", currentDate, (8 + i));
                model.TimeZone = DateTime.Parse(date).ToString("hh:mm tt");

                if (events != null && events.Count > 0)
                    model.Events = GetAllEventsBy(events, DateTime.Parse(start), DateTime.Parse(end));

                calendarList.Add(model);
            }

            return calendarList;
        }
        #endregion

        #region Private Method
        private List<Events> GetAllEventsBy(List<CalendarInfoEx> calendars, DateTime startDate, DateTime endDate)
        {
            List<Events> list = new List<Events>();

            var events = calendars.Where(c => c.StartDate >= startDate && c.StartDate <= endDate).OrderBy(c => c.StartDate);
            foreach (var item in events)
            {
                Events model = new Events();
                model.TimeEvent = item.StartDate.ToString("hh:mm tt");
                model.LeadName = item.LeadName;
                model.LeadUrl = string.Format("/Lead/Edit/{0}", item.Id);
                model.Title = item.Title;
                list.Add(model);
            }

            return list;
        }

        #endregion
    }
}